﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.IO;
using System.Security.Cryptography;
//using PegasusImagingActiveXImagXpress9;
//using Tamir.SharpSsh;
using TransferFile;
using Publicador.CartagenaWS;
using System.Data;
using System.Windows.Forms;
using System.Drawing;
using System.Reflection;

namespace Publicador
{
    enum Md5Sum { checksum, azuresum };

    public class Divipol
    {
        public string divipol = null;
        public string checksum = null;
        public string azuresum = null;
    }

    public class E14
    {
        int Contador = 0;
        private string MUNICIPIO = "";
        private string USUARIO = "";
        static SQLiteConnection conexion;
        private System.Windows.Forms.TextBox _Novedades = null;
        private System.Windows.Forms.TextBox _Publicados = null;
        private System.Windows.Forms.ToolStripStatusLabel _toolStripStatusLabel = null;
        private System.Windows.Forms.GroupBox _groupBox = null;
        private bool Procesando = false;
        public bool Activo = false;

        public E14(ref System.Windows.Forms.TextBox Publicados, ref System.Windows.Forms.TextBox Novedades, ref System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel, ref System.Windows.Forms.GroupBox groupBox)
        {
            _Novedades = Novedades;
            _Publicados = Publicados;
            _toolStripStatusLabel = toolStripStatusLabel;
            _groupBox = groupBox;
            if (!File.Exists("Publicador"))
            {
                System.Windows.Forms.MessageBox.Show("No se encuentra el archivo de base de datos por favor actualizar el aplicativo", "E14", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                System.Environment.Exit(0);
            }
            conexion = new SQLiteConnection(Publicador.Properties.Settings.Default.E14ConnectionString);
            //TODO
            //Autenticar("NEIVA");
        }

        #region functions DB

        private Divipol GetDivipol(string divipol)
        {
            try
            {
                conexion.Open();
                Divipol res = new Divipol();
                string consulta = "select checksum, azuresum  from divipol d where d.divipol='" + divipol + "'";
                if (MUNICIPIO != "TODOS")
                    consulta += " and nombrempio='" + this.MUNICIPIO + "'";
                SQLiteCommand cmd = new SQLiteCommand(consulta, conexion);
                SQLiteDataReader datos = cmd.ExecuteReader();
                while (datos.Read())
                {
                    res.divipol = divipol;
                    res.checksum = Convert.ToString(datos[0]);
                    res.azuresum = Convert.ToString(datos[1]);
                }
                return res;
            }
            finally
            {
                conexion.Close();
            }
        }

        private void SetChecksum(Divipol divipol, Md5Sum TypeSum, string sum)
        {
            try
            {
                conexion.Open();
                string creacion = "update divipol set " + TypeSum.ToString() + "='" + sum + "' where divipol='" + divipol.divipol + "'";
                SQLiteCommand cmd = new SQLiteCommand(creacion, conexion);
                cmd.ExecuteNonQuery();
            }
            finally
            {
                conexion.Close();
            }
        }

        public bool Autenticar(string MUNICIPIO)
        {
            bool res = false;
            try
            {
                conexion.Open();
                string consulta = "SELECT COUNT(iddivipol) AS Expr1 FROM divipol WHERE (nombrempio = '" + MUNICIPIO + "')";
                SQLiteCommand cmd = new SQLiteCommand(consulta, conexion);
                SQLiteDataReader datos = cmd.ExecuteReader();
                while (datos.Read())
                {
                    if (Convert.ToInt32(datos[0]) > 0)
                        res = true;
                }
                return res;
            }
            finally
            {
                conexion.Close();
            }
        }

        public DataTable ObtenerPendientes(string MUNICIPIO, string PUESTO = "TODOS")
        {
            try
            {
                string WHERE = "";
                if(MUNICIPIO != "TODOS")
                    WHERE = (WHERE == "" ? " WHERE " : "") + " (nombrempio = '" + MUNICIPIO + "') ";
                if (PUESTO != "TODOS")
                {
                    WHERE += (WHERE == "") ? " WHERE " : " AND ";
                    WHERE += " (c.centro = '" + PUESTO + "') ";
                }
                //string strSQL = "SELECT c.centro, d.nombrepuesto, d.mesa, case when d.checksum is null then \"Pendiente\" else \"Publicado\" end as estado FROM divipol d inner join centro c on (d.coddpto || d.codmpio || d.codzona || d.codpuesto) = c.divipol " + WHERE + " ORDER BY d.estado desc, d.nombrepuesto, d.mesa";
                string strSQL = "SELECT \"CHOCO\" as centro, d.nombrepuesto, d.mesa, case when d.checksum is null then \"Pendiente\" else \"Publicado\" end as estado FROM divipol d " + WHERE + " ORDER BY d.estado desc, d.nombrepuesto, d.mesa";
                SQLiteDataAdapter Datos = new SQLiteDataAdapter(strSQL, conexion);
                DataTable dtdatos = new DataTable();
                Datos.Fill(dtdatos);
                return dtdatos;
            }
            catch { return null; }
        }

        public DataTable ObtenerPuestos(string MUNICIPIO)
        {
            try
            {
                string WHERE = "";
                //if (MUNICIPIO != "TODOS")
                //    WHERE = " WHERE (nombrempio = '" + MUNICIPIO + "') ";
                string strSQL = "select \" TODOS\" as nombrepuesto union select distinct centro from centro " + WHERE + " ORDER BY centro";                
                SQLiteDataAdapter Datos = new SQLiteDataAdapter(strSQL, conexion);
                DataTable dtdatos = new DataTable();
                Datos.Fill(dtdatos);
                return dtdatos;
            }
            catch { return null; }
        }

        public DataTable ObtenerMunicipios()
        {
            try
            {                
                string strSQL = "SELECT DISTINCT nombrempio FROM divipol ORDER BY nombrempio";
                SQLiteDataAdapter Datos = new SQLiteDataAdapter(strSQL, conexion);
                DataTable dtdatos = new DataTable();
                Datos.Fill(dtdatos);
                return dtdatos;
            }
            catch { return null; }
        }

        #endregion

        #region functions files

        public string ObtenerMd5File(string FilePath)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = File.OpenRead(FilePath))
                {
                    return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
                }
            }
        }

        #endregion

        #region Proceso

        public void Iniciar(string MUNICIPIO, string USUARIO)
        {
            this.MUNICIPIO = MUNICIPIO;
            this.USUARIO = USUARIO;
            if (Procesando)
                return;
            Procesando = true;     
            
            foreach (string filePaths in Directory.GetFiles(Properties.Settings.Default.E14Digitalizacion, "*" + Properties.Settings.Default.E14Extension))
            {
                _toolStripStatusLabel.BackColor = Color.Silver;                
                _toolStripStatusLabel.Text = String.Empty;
                Procesar(filePaths.Trim());                
                //Form.ActiveForm.Refresh();
                Application.DoEvents();
            }
            Procesando = false;
            _toolStripStatusLabel.BackColor = Color.Red;
            _toolStripStatusLabel.Text = "Esperando Cambios";
        }

        private void Procesar(string filePaths)
        {
            if (!Activo)
                return;
            string CodDiv = Path.GetFileNameWithoutExtension(filePaths);
            Divipol divipol = GetDivipol(CodDiv);
            if (divipol.divipol != null)
            {
                if (!CompararMd5(divipol, filePaths))
                {
                    _toolStripStatusLabel.Text = "Procesando: " + CodDiv;
                    if (true)//Resize(filePaths))
                    {
                        try
                        {
                            string imgTmp = Path.GetDirectoryName(filePaths) + @"\" + Path.GetFileNameWithoutExtension(filePaths);
                            if (Properties.Settings.Default.E14Extension == ".jpg")
                                imgTmp += ".ptf";
                            else
                                imgTmp += Properties.Settings.Default.E14Extension;
                            File.Copy(imgTmp, @"C:\DIGITALIZACION\AZURE\" + Path.GetFileNameWithoutExtension(filePaths) + Properties.Settings.Default.E14Extension, true);
                        }
                        catch (Exception)
                        {                                                        
                        }
                        string RutaPub = Properties.Settings.Default.E14Publicacion;
                        if (Transmitir(filePaths, ref RutaPub))
                        {
                            try
                            {                                                                
                                wsvalle WS = new wsvalle();
                                WS.CambioEstado(CodDiv, "Pub", USUARIO);
                                string imgExt = "";
                                if (Properties.Settings.Default.E14Extension == ".jpg")
                                    imgExt+= ".ptf";
                                else
                                    imgExt += Properties.Settings.Default.E14Extension;
                                WS.InsertarRuta(CodDiv, RutaPub + @"\" + CodDiv + imgExt);
                                _Publicados.Text = "(" + CodDiv + ") Transmitido " + System.Environment.NewLine + _Publicados.Text;
                                _Publicados.Select(_Publicados.Text.Length, 0);
                                SetChecksum(divipol, Md5Sum.checksum, ObtenerMd5File(filePaths));
                                Contador++;
                                _groupBox.Text = "Transmitidos: " + Contador.ToString();
                            }
                            catch (Exception E)
                            {
                                _Novedades.Text = E.Message + System.Environment.NewLine + _Novedades.Text;
                            }
                        }
                    }
                }
            }
            else
            {
                _Novedades.Text = "(" + CodDiv + ") Codigo no pertenece a " + MUNICIPIO + System.Environment.NewLine + _Novedades.Text;
                _Novedades.Select(_Novedades.Text.Length, 0);
            }
        }

        private bool Transmitir(string filePaths, ref string RutaPub)
        {
            bool res = false;
            try
            {
                RutaPub = (Properties.Settings.Default.E14Transmision == "wcf") ? @"\\192.168.70.38\CHOCHO\imagenes" : Properties.Settings.Default.E14Publicacion;
                switch (Properties.Settings.Default.E14Transmision)
                {
                    case "ftp":
                        {
                            string ftphost = Properties.Settings.Default.ftphost;
                            string ftpuser = Properties.Settings.Default.ftpuser;
                            string ftppass = Properties.Settings.Default.ftppass;

                            string imgTmp = Path.GetDirectoryName(filePaths) + @"\" + Path.GetFileNameWithoutExtension(filePaths);
                            if (Properties.Settings.Default.E14Extension == ".jpg")
                                imgTmp += ".ptf";
                            else
                                imgTmp += Properties.Settings.Default.E14Extension;
                            string ruta = ftphost;

                            using (System.Net.WebClient client = new System.Net.WebClient())
                            {
                                client.Credentials = new System.Net.NetworkCredential(ftpuser, ftppass);
                                
                                client.UploadFile(ruta + "/" + Path.GetFileNameWithoutExtension(Path.GetFileName(filePaths)) + ".jpg", "STOR", imgTmp);
                            }
                            break;
                        }
                    /*
                    case "sftp":
                        {
                            string hostName = Properties.Settings.Default.sftphost;
                            string userName = Properties.Settings.Default.sftpuser;
                            string password = Properties.Settings.Default.sftppass;
                            int port = Convert.ToInt32(Properties.Settings.Default.sftpport);
                            string fromFilePaths = Path.GetDirectoryName(filePaths) + @"\" + Path.GetFileNameWithoutExtension(filePaths) + ".ptf";
                            string toFilePath = Path.GetFileNameWithoutExtension(Path.GetFileName(filePaths)) + ".jpg";
                            Sftp sftp = null;
                            try
                            {
                                sftp = new Sftp(hostName, userName, password);
                                sftp.Connect(port);
                                sftp.Put(fromFilePaths, toFilePath);
                                sftp.Close();
                            }
                            catch (Exception)
                            {
                                sftp.Close();
                            }
                            break;
                        }
                    */
                    case "ws":
                        {                            
                            string imgTmp = Path.GetDirectoryName(filePaths) + @"\" + Path.GetFileNameWithoutExtension(filePaths);
                            if (Properties.Settings.Default.E14Extension == ".jpg")
                                imgTmp += ".ptf";
                            else
                                imgTmp += Properties.Settings.Default.E14Extension;
                            //string filename = System.IO.Path.GetTempPath() + @"\" + Path.GetFileNameWithoutExtension(Path.GetFileName(filePaths)) + ".jpg";
                            wsvalle WS = new wsvalle();
                            string resws = WS.SubirImagen(Path.GetFileNameWithoutExtension(Path.GetFileName(filePaths)), ObtenerBase64(imgTmp));
                            break;
                        }
                    case "wcf":
                        {
                            string imgExt = "";                            
                            if (Properties.Settings.Default.E14Extension == ".jpg")
                                imgExt = ".ptf";
                            else
                                imgExt = Properties.Settings.Default.E14Extension;
                            string imgTmp = Path.GetDirectoryName(filePaths) + @"\" + Path.GetFileNameWithoutExtension(filePaths) + imgExt;
                            string filename = System.IO.Path.GetTempPath() + @"\" + Path.GetFileNameWithoutExtension(Path.GetFileName(filePaths)) + imgExt;
                            File.Copy(imgTmp, filename, true);
                            TransferFile.TransferFile.EnviarArchivo(filename);
                            break;
                        }
                }
                res = true;
            }
            catch (Exception E)
            {
                if (Properties.Settings.Default.E14Transmision == "wcf")
                {
                    try
                    {
                        string imgTmp = Path.GetDirectoryName(filePaths) + @"\" + Path.GetFileNameWithoutExtension(filePaths);
                        if (Properties.Settings.Default.E14Extension == ".jpg")
                            imgTmp += ".ptf";
                        else
                            imgTmp += Properties.Settings.Default.E14Extension;
                        wsvalle WS = new wsvalle();
                        string resws = WS.SubirImagen(Path.GetFileNameWithoutExtension(Path.GetFileName(filePaths)), ObtenerBase64(imgTmp));
                        RutaPub = Properties.Settings.Default.E14Publicacion;
                        return true;
                    }
                    catch(Exception)
                    {
                        _Novedades.Text = E.Message + System.Environment.NewLine + _Novedades.Text;
                        res = false;
                    }
                }
                _Novedades.Text = E.Message + System.Environment.NewLine + _Novedades.Text;
                res = false;
            }
            return res;
        }

        public bool Resize(string filePaths)
        {
            if (Properties.Settings.Default.E14Extension != ".jpg")
                return true;
            bool res = false;
            /*
            string imgOri = filePaths;
            string imgTmp = Path.GetDirectoryName(filePaths) + @"\" + Path.GetFileNameWithoutExtension(filePaths) + ".ptf";
            ImagXpress aImg = new ImagXpress();
            aImg.UnlockRuntime(1908208383, 373713104, 1341134731, 29785);
            File.Copy(imgOri, imgTmp, true);
            aImg.FileName = imgTmp;
            aImg.IResX = 100;
            aImg.IResY = 100;
            aImg.SaveFileName = imgTmp;
            aImg.Resize(266, 1176);
            aImg.SaveFileType = enumSaveFileType.FT_JPEG;
            aImg.SaveMultiPage = false;
            aImg.SaveFile();
            */
            res = true;
            return res;
        }

        public string ObtenerBase64(string sNombreArchivo)
        {
            string sBase64 = "";
            FileStream fs = new FileStream(sNombreArchivo, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            byte[] bytes = new byte[(int)fs.Length];
            try
            {
                br.Read(bytes, 0, bytes.Length);
                sBase64 = Convert.ToBase64String(bytes);
                return sBase64;
            }
            catch
            {
                return "-1";
            }
            finally
            {
                fs.Close();
                fs = null;
                br = null;
                bytes = null;
            }
        }


        #endregion

        #region functions common

        public bool CompararMd5(Divipol divipol, string FilePath)
        {
            bool res = false;
            if (ObtenerMd5File(FilePath) == divipol.checksum)
                res = true;
            return res;
        }

        public bool CompararMd5Azure(Divipol divipol, string FilePath)
        {
            bool res = false;
            if (ObtenerMd5File(FilePath) == divipol.azuresum)
                res = true;
            return res;
        }

        public bool ValidaVersion() {
            bool Res = true;            
            wsvalle WS = new wsvalle();
            string version = (string)WS.ObtenerVersion();            
            Version v = Assembly.GetExecutingAssembly().GetName().Version;
            string About = string.Format(@"{0}.{1}.{2}.{3}", v.Major, v.Minor, v.Build, v.Revision);
            if (version == About)
                Res = true;
            else
                Res = false;
            return Res;
        }

        #endregion
    }
}
